package com.hly.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {

    public static void main(String[] args) {
//        String fileUrl = " "; // 这里替换为你的文件URL
        String fileUrl = ""; // 这里替换为你的文件URL
        String saveDir = "D:\\tmp"; // 这里替换为你希望保存文件的目录
        String fileName = "file.xlsx"; // 你可以修改为你希望保存的文件名
        try {
            downloadFile(fileUrl, saveDir, fileName);
            System.out.println("文件下载成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downloadFile(String fileUrl, String saveDir, String fileName) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//        httpConn.setRequestMethod("GET");
//        httpConn.setDoInput(true);
//        httpConn.setDoOutput(true);
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应码是否为200，即"OK"
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String filePath = saveDir + File.separator + fileName;
            File outputFile = new File(filePath);

            // 创建输出文件所需的目录
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            // 打开连接
            InputStream inputStream = httpConn.getInputStream();
            OutputStream outputStream = new FileOutputStream(outputFile);

            byte[] buffer = new byte[4096];
            int bytesRead;

            // 从输入流中读取数据，并写入到输出流中
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 刷新并关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } else {
            throw new Exception("HTTP Error Code: " + responseCode);
        }
        httpConn.disconnect();
    }
}